package com.zhiyou100.cudr;

import com.zhiyou100.dao.StudentDao;
import com.zhiyou100.entityclass.Student;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @packageName: ${NAME}
 * @className: ${PACKAGE_NAME}
 * @Description: TODO
 * @author: yang
 * @date: 7/20/20
 */
@WebServlet(name = "addOne", urlPatterns = "/addOne")
public class AddOne extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        // 设定编码集
        response.setContentType("text/html;charset=UTF-8");
        // 设定类型

        // 获取参数
        String sid = request.getParameter("sid");
        String sname = request.getParameter("sname");
        String sex = request.getParameter("sex");
        String sage = request.getParameter("sage");
        String scid = request.getParameter("scid");

        StudentDao studentDao = new StudentDao();

        // 对参数进行合理性判断 true 或者 false
        boolean reasonableJustification = studentDao.reasonableJustification(sid, sname, sex, sage, scid);
        if (reasonableJustification) {
            // 合理，创建对象，添加
            System.out.println("合理");
            System.out.println(sid+" "+sname+" "+sex+" "+sage+" "+scid);
            Student m  = new Student(Long.parseLong(sid)
                    , sname, sex.equals("m") ? "男" : "女",
                    Long.parseLong(sage),
                    Long.parseLong(scid));

            boolean b = studentDao.addOne(m);
            request.setAttribute("isAdd", b);
            request.getRequestDispatcher("/jsp/addOne.jsp").forward(request, response);
        } else {
            System.out.println("不合理");
            // 不合理，不创建，不添加，传入 false
            request.setAttribute("isAdd", false);
            request.getRequestDispatcher("/jsp/addOne.jsp").forward(request, response);

        }


    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
